package com.ihealthway.all.groupbuy.modules.front;

import com.ihealthway.all.commons.Constants;
import com.ihealthway.all.groupbuy.services.GoodsService;
import com.ihealthway.all.groupbuy.services.ImageLibraryService;
import com.ihealthway.all.groupbuy.services.UserInfoService;
import com.ihealthway.all.groupbuy.vo.Goods;
import com.ihealthway.all.groupbuy.vo.ImageLibrary;
import com.ihealthway.all.groupbuy.vo.UserInfo;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Front home page class
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@At("/front/shop")
@IocBean
public class ShopIndexModule {

    private static final Log logger = Logs.get();

    @Inject
    private ImageLibraryService imgLibService;

    @Inject
    private GoodsService goodsService;

    @Inject
    private UserInfoService userInfoService;


    @At
    @Ok("beetl:front/shop_index.jsp")
    public void home(HttpServletRequest req) {
        logger.info("Shop Index Info...");
        // 1. search top ad shop info
        List<ImageLibrary> ads = imgLibService.getShopAdImgs();

        // 2. search top 30 product
        UserInfo userInfo = (UserInfo) req.getSession().getAttribute(Constants.WECHAT_LOGIN_SESSION);
        Integer companyId = userInfo.getCompanyId();
        List<Goods> goods = goodsService.getGoodsListIOnFront(companyId,null, null);

        req.setAttribute("ads", ads);
        req.setAttribute("gs", goods);
    }

    @At
    @Ok("proxy:${obj}")
    public String checkUserStatus(@Param("openId") String openId, @Param("re") String redirectURL, HttpServletRequest req) {

        String sub = "/static/html/sub.html";
        String register = "/front/personal/register.do";

        UserInfo userInfo = userInfoService.getRegisterUser(openId);
        if (userInfo!=null) {

            req.getSession().setAttribute(Constants.WECHAT_LOGIN_SESSION, userInfo);

            if (userInfo.getCompanyId()!=null) {
                String ui = redirectURL.replace("0", "/");
                ui = ui.replace("1", ".");
                ui = ui.replace("2", "?");
                ui = ui.replace("3", "=");
                logger.infof("Session create redirect url: %s", ui);
                return ui;
            }

            return register+"?re="+redirectURL;
        }

        return sub;
    }

}
